/*
 * Copyright (c) 2015, 张涛.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sudworth.themvp.presenter;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.sudworth.themvp.model.IModel;
import com.sudworth.themvp.view.IDelegate;
import com.sudworth.themvp.annotation.Mvp;

import javax.inject.Inject;

/**
 * Presenter base class for Activity
 * Presenter层的实现基类
 *
 * @param <T> View delegate class type
 * @author kymjs (http://www.kymjs.com/) on 10/23/15.
 */
public abstract class ActivityPresenter<T extends IDelegate, M extends IModel> extends AppCompatActivity {

    /**
     * 添加这个 @Inject 注解为了是让 这两个字段具有Dagger2的能力，普通使用并无任何影响
     */
    @Inject
    protected T viewDelegate;

    @Inject
    protected M mModel;

    public ActivityPresenter() {
        if(canMvp()) return;
        Mvp annotation = getClass().getAnnotation(Mvp.class);
        viewDelegate = createIDelegateInstance(annotation);
        mModel = createIModelInstance(annotation);
    }

    protected boolean canViewBinding() {
        return false;
    }

    protected View onResetContentView() {
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewDelegate.create(getLayoutInflater(), null, savedInstanceState);
        viewDelegate.setActivity(this);
        if(canViewBinding()) {
            setContentView(onResetContentView());
        } else {
            setContentView(viewDelegate.getRootView());
        }
        initToolbar();
        viewDelegate.setFragmentManager(getSupportFragmentManager());
        viewDelegate.initWidget();
        bindEvenListener();
    }

    @Override
    protected void onStart() {
        super.onStart();
        viewDelegate.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        viewDelegate.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        viewDelegate.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        viewDelegate.onStop();
    }

    protected void bindEvenListener() {
    }

    protected void initToolbar() {
        Toolbar toolbar = viewDelegate.getToolbar();
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if(canMvp()) return;
        Mvp annotation = getClass().getAnnotation(Mvp.class);
        if (viewDelegate == null) {
            viewDelegate = createIDelegateInstance(annotation);
        }
        if(mModel == null) {
            mModel = createIModelInstance(annotation);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (viewDelegate.getOptionsMenuId() != 0) {
            getMenuInflater().inflate(viewDelegate.getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        if(viewDelegate != null) {
            viewDelegate.destroy();
            viewDelegate = null;
        }
        if(mModel != null) {
            mModel.onDestroy();
            mModel = null;
        }
        super.onDestroy();
    }

    private M createIModelInstance(@NonNull Mvp annotation) {
        if (!isIModel(annotation)) {
            StringBuilder sb = new StringBuilder(this.getClass().getName());
            sb.append("-> ")
                    .append(annotation.view().getName())
                    .append(": 必须是IModel的实现类");
            throw new RuntimeException(sb.toString());
        }
        M m;
        try {
            m =  (M) annotation.model().newInstance();
        } catch (IllegalAccessException | java.lang.InstantiationException e) {
            throw new RuntimeException("create IModel error: " + e.toString());
        }
        return m;
    }

    private T createIDelegateInstance(@NonNull Mvp annotation) {
        if (!isIDelegate(annotation)) {
            StringBuilder sb = new StringBuilder(this.getClass().getName());
            sb.append("-> ")
                    .append(annotation.view().getName())
                    .append(": 必须是IDelegate的实现类");
            throw new RuntimeException(sb.toString());
        }
        T t;
        try {
            t = (T) annotation.view().newInstance();
        } catch (IllegalAccessException | java.lang.InstantiationException e) {
            throw new RuntimeException("create IDelegate error: " + e.toString());
        }
        return t;
    }

    private boolean isIModel(@NonNull Mvp annotation) {
        return IModel.class.isAssignableFrom(annotation.model());
    }

    private boolean isIDelegate(@NonNull Mvp annotation) {
        return IDelegate.class.isAssignableFrom(annotation.view());
    }

    private boolean canMvp() {
        return null == getClass().getAnnotation(Mvp.class);
    }
}
